import pandas as pd
import numpy as np
import math
import random
def sigmod(iX,dimension):#iX is a matrix with a dimension
    if dimension==1:
        for i in range(len(iX)):
            iX[i] = 1 / (1 + math.exp(-iX[i]))
    else:
        for i in range(len(iX)):
            iX[i] = sigmod(iX[i],dimension-1)
    return iX
dataset = pd.read_csv('C:\\Users\\Szper\\Desktop\\xigua.csv', delimiter=",")

attributeMap={}
attributeMap['浅白']=0
attributeMap['青绿']=0.5
attributeMap['乌黑']=1

attributeMap['蜷缩']=0
attributeMap['稍蜷']=0.5
attributeMap['硬挺']=1

attributeMap['沉闷']=0
attributeMap['浊响']=0.5
attributeMap['清脆']=1

attributeMap['模糊']=0
attributeMap['稍糊']=0.5
attributeMap['清晰']=1

attributeMap['凹陷']=0
attributeMap['稍凹']=0.5
attributeMap['平坦']=1

attributeMap['硬滑']=0
attributeMap['软粘']=1
attributeMap['否']=0
attributeMap['是']=1
dataset=np.array(dataset)
m,n=np.shape(dataset)
print (m, n)
for i in range(m):
    for j in range(n):
        if dataset[i,j] in attributeMap:
            dataset[i, j] = attributeMap[dataset[i, j]]
        dataset[i, j] = round(dataset[i,j],3)
#print (dataset)
trueY = dataset[:, n-1]
X = dataset[:, :n-1]
print (X)
maxIter=5000
d=n #输入向量维度
l=1 #输出向量维度
q=d+1 #隐层神经元个数
v = [[random.random() for i in range(q)] for j in range(d-1)]  #输入层到隐层的连接权重，v=d*q
print (v)
w = [[random.random() for i in range(l)] for j in range(q)]  #隐层到输出层的连接权重，w=q*l
theta = [random.random() for i in range(l)]  #l个输出层神经元的阈值
gamma = [random.random() for i in range(q)]  #q个隐层神经元的阈值
rate=0.2
alpha=np.dot(X[1], v)
print ("alpha:", alpha)
while (maxIter > 0):
    maxIter -= 1
    sumE = 0
    for i in range (m):
        alpha=np.dot(X[i], v)
        b = sigmod(alpha-gamma, 1)
        beta=np.dot(b, w)
        pridictY=sigmod(beta-theta, 1)
        E=sum((pridictY-trueY[i]) ** 2)/2
        sumE+=E
        g = pridictY*(1-pridictY)*(trueY[i]-pridictY)
        e=b*(1-b)*((np.dot(w, g.T)).T)
        w+=rate * np.dot(b.reshape((q, 1)), g.reshape((1,1)))
        theta -= rate*g
        v+=rate*np.dot(X[i].reshape((d-1,1)),e.reshape((1,q)))
        gamma-=rate*e
def predict(iX):
    alpha = np.dot(iX, v)  # p101 line 2 from bottom, shape=m*q
    b=sigmod(alpha-gamma,2)#b=f(alpha-gamma), shape=m*q
    beta = np.dot(b, w)  # shape=(m*q)*(q*l)=m*l
    pridictY=sigmod(beta - theta,2)  # shape=m*l ,p102--5.3
    return pridictY
predict(X)
py = predict(X)
for i in range(len(py)):
    if py[i][0] < 0.5:
        py[i][0] = 0
    else:
        py[i][0] = 1
print (py.T)
print (trueY)